﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using ProxyTool.ControlAnimation;
using ProxyTool.Controls;
using ProxyTool.Forms;
using ProxyTool.Models;
using ProxyTool.Services;
using ProxyTool.Services.Utils;
using ProxyTool.Setting;
using ProxyTool.Utils;

namespace ProxyTool
{
    public partial class MainForm : Form
    {
        private const string DefaultFileFilters = @"json files (*.json)|*.json";
        private const string HomeTabPageName = "homeTabPage";

        public MainForm()
        {
            InitializeComponent();
            //设置主窗口标题
            SetMainFormText();
            //整行选择
            bpsvResultDataGrid.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            bpsvResultDataGrid.CellMouseDoubleClick += bpsvResultDataGrid_CellMouseDoubleClick;
            proxyTabControl.OnTabPageClosing += OnTabPageClosing;
        }

        /// <summary>
        ///     设置主窗口标题
        /// </summary>
        private void SetMainFormText()
        {
            Text = string.Format("服务测试工具-{0}", SettingManagement.Instance.Setting.U9URI);
            labelVersion.Text = string.Format("版本 : {0}", Application.ProductVersion);
        }

        /// <summary>
        ///     是否关闭
        /// </summary>
        /// <param name="e"></param>
        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);
            ShowStatusMsg();
            //TabPage关闭时
            var proxyTabPages = new List<TabPage>();
            foreach (TabPage tabPage in proxyTabControl.TabPages)
            {
                if (tabPage.Tag == null) continue;
                if (tabPage.Tag is ProxyEditControl)
                {
                    proxyTabPages.Add(tabPage);
                }
            }

            if (proxyTabPages.Count > 0)
            {
                var dialogResult = MessageBox.Show("是否全部保存?", "提醒", MessageBoxButtons.YesNoCancel);
                switch (dialogResult)
                {
                    case DialogResult.Cancel:
                        e.Cancel = true;
                        return;
                    case DialogResult.Yes:
                        foreach (var tabPage in proxyTabPages)
                        {
                            SaveFile(tabPage, false);
                        }

                        break;
                }
            }
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            //停止所有的调试
            SettingManagement.Instance.StopAllDebug();
        }

        

        #region 首页

        private void linkLabelU9WS_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            OpenUrl("https://gitee.com/mutongtech/wss");
        }

        private void linkLabelJSonEditor_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            OpenUrl("https://github.com/zetoken/JSon-Editor");
        }

        private void linkLabelRestSharp_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            OpenUrl("https://github.com/restsharp/RestSharp");
        }

        private void linkLabelNewtonsoftJson_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            OpenUrl("https://www.newtonsoft.com/json");
        }

        private void linkLabelHarmony_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            OpenUrl("https://github.com/pardeike/Harmony");
        }

        private void OpenUrl(string url)
        {
            Process.Start("iexplore.exe", url);
        }

        #endregion

        #region 其它

        /// <summary>
        ///     是否关闭
        /// </summary>
        /// <param name="tabPage"></param>
        /// <returns></returns>
        private bool OnTabPageClosing(TabPage tabPage)
        {
            ShowStatusMsg();
            if (tabPage.Tag != null && tabPage.Tag is ProxyEditControl)
            {
                var proxyEditControl = tabPage.Tag as ProxyEditControl;
                var isProxyChange = true;
                if (!string.IsNullOrEmpty(proxyEditControl.ProxyJsonFileName))
                {
                    if (File.Exists(proxyEditControl.ProxyJsonFileName))
                    {
                        var oldJsonString = FileHelper.ReadFile(proxyEditControl.ProxyJsonFileName, Encoding.UTF8);
                        var newJsonString =
                            JsonHelper.ObjectToJsonString(proxyEditControl.GetProxyData(), Formatting.None);
                        if (oldJsonString == newJsonString)
                            isProxyChange = false;
                    }
                }

                if (isProxyChange)
                {
                    var dialogResult = MessageBox.Show("是否保存?", "提醒", MessageBoxButtons.YesNoCancel);
                    switch (dialogResult)
                    {
                        case DialogResult.Cancel:
                            return false;
                        case DialogResult.Yes:
                            SaveFile(tabPage, false);
                            break;
                    }
                }

                //停止代理事务调试
                proxyEditControl.StopProxyTypeDebug();
                return true;
            }

            return false;
        }

        /// <summary>
        ///     输出状态消息
        /// </summary>
        /// <param name="msg"></param>
        public void ShowStatusMsg(string msg = "")
        {
            msgToolStripStatusLabel.Text = msg;
        }

        #endregion

        #region 菜单按钮

        /// <summary>
        ///     新建
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var createProxyFrom = new CreateProxyForm();
            if (createProxyFrom.ShowDialog() == DialogResult.OK)
            {
                using (new ControlAnimatorObject(mainStatusStrip))
                {
                    var name = createProxyFrom.Name;
                    string proxyType = createProxyFrom.GetProxyType();
                    bool useDataContract = createProxyFrom.GetUseDataContract();
                    int requestDataMaxExpandDepth = SettingManagement.Instance.Setting.DefaultRequestDataMaxExpandDepth;
                    ProxyData proxyData;
                    try
                    {
                        if (string.IsNullOrWhiteSpace(proxyType))
                            throw new ProxyToolException("代理类型为空");
                        proxyData = ProxyData.GetProxyData(proxyType, useDataContract, requestDataMaxExpandDepth);
                    }
                    catch (Exception ex)
                    {
                        if (MessageBox.Show(string.Format("创建代理对象失败 \r\n错误原因:{0} \r\n是否继续创建?", ex.Message), "提醒确认",
                                MessageBoxButtons.OKCancel) ==
                            DialogResult.OK)
                        {
                            proxyData = new ProxyData();
                            proxyData.ProxyType = proxyType;
                            proxyData.UseDataContract = useDataContract;
                        }
                        else
                        {
                            return;
                        }
                    }

                    proxyTabControl.AddProxyTabPage(name, proxyData);
                }
            }
        }

        /// <summary>
        ///     打开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowStatusMsg();
            var openFileDialog = new OpenFileDialog
            {
                Filter = @"json files (*.json)|*.json|All files (*.*)|*.*",
                FilterIndex = 1,
                RestoreDirectory = true
            };
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                using (new ControlAnimatorObject(mainStatusStrip))
                {
                    var fileFullName = openFileDialog.FileName;
                    var fileName = Path.GetFileNameWithoutExtension(fileFullName);
                    var jsonString = FileHelper.ReadFile(fileFullName, Encoding.UTF8);
                    var proxyData = JsonHelper.ObjectFromJsonString<ProxyData>(jsonString);
                    var tabPage = proxyTabControl.AddProxyTabPage(fileName, proxyData);
                    var proxyEditConrol = ProxyTabControl.GetProxyEditConrol(tabPage);
                    if (proxyEditConrol == null) return;
                    proxyEditConrol.ProxyJsonFileName = fileFullName;
                }

                ShowStatusMsg("加载成功");
            }
        }

        /// <summary>
        ///     保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowStatusMsg();
            SaveFile(false);
        }

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowStatusMsg();
            SaveFile(true);
        }

        /// <summary>
        ///     全部保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void saveAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (TabPage tabPage in proxyTabControl.TabPages)
            {
                if (tabPage.Name == HomeTabPageName) continue;
                SaveFile(tabPage, false);
            }
        }

        /// <summary>
        ///     保存文件
        /// </summary>
        /// <param name="isSaveAs"></param>
        private void SaveFile(bool isSaveAs)
        {
            SaveFile(proxyTabControl.SelectedTab, isSaveAs);
        }

        /// <summary>
        ///     保存文件
        /// </summary>
        /// <param name="tabPage"></param>
        /// <param name="isSaveAs"></param>
        public void SaveFile(TabPage tabPage, bool isSaveAs)
        {
            proxyTabControl.SelectedTab = tabPage;
            var proxyEditConrol = ProxyTabControl.GetProxyEditConrol(tabPage);
            if (proxyEditConrol == null) return;
            var proxyData = proxyEditConrol.GetProxyData();
            var proxyJsonString = JsonHelper.ObjectToJsonString(proxyData, Formatting.None);
            var proxyJsonFileName = string.Empty;
            if (isSaveAs || string.IsNullOrEmpty(proxyEditConrol.ProxyJsonFileName))
            {
                var saveFileDialog = new SaveFileDialog
                {
                    Filter = DefaultFileFilters,
                    FilterIndex = 1,
                    RestoreDirectory = true,
                    FileName = tabPage.Text.Trim()
                };
                if (saveFileDialog.ShowDialog() != DialogResult.OK) return;
                proxyJsonFileName = saveFileDialog.FileName;
            }
            else
            {
                proxyJsonFileName = proxyEditConrol.ProxyJsonFileName;
            }

            FileHelper.WriteFile(proxyJsonFileName, proxyJsonString, Encoding.UTF8);
            tabPage.Text = Path.GetFileNameWithoutExtension(proxyJsonFileName) + " ";
            proxyEditConrol.ProxyJsonFileName = proxyJsonFileName;
            ShowStatusMsg("保存成功");
        }

        /// <summary>
        ///     关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            proxyTabControl.CloseTabPage(proxyTabControl.SelectedTab);
        }

        private void existToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        /// <summary>
        ///     设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void settingToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var settingForm = new SettingForm();
            if (settingForm.ShowDialog() == DialogResult.OK)
            {
                SetMainFormText();
                settingForm.Close();
            }
        }

        #endregion

        #region 工具栏按钮

        private void newToolStripButton_Click(object sender, EventArgs e)
        {
            newToolStripMenuItem_Click(sender, e);
            ;
        }

        private void openToolStripButton_Click(object sender, EventArgs e)
        {
            openToolStripMenuItem_Click(sender, e);
        }

        private void saveToolStripButton_Click(object sender, EventArgs e)
        {
            saveToolStripMenuItem_Click(sender, e);
        }

        private void saveAndCloseToolStripButton_Click(object sender, EventArgs e)
        {
            saveToolStripMenuItem_Click(sender, e);
        }

        private void saveAlltoolStripButton_Click(object sender, EventArgs e)
        {
            saveAllToolStripMenuItem_Click(sender, e);
        }

        private void closeToolStripButton_Click(object sender, EventArgs e)
        {
            closeToolStripMenuItem_Click(sender, e);
        }

        private void helpToolStripButton_Click(object sender, EventArgs e)
        {
            if (proxyTabControl.TabPages[HomeTabPageName] == null) return;
            proxyTabControl.SelectedTab = proxyTabControl.TabPages[HomeTabPageName];
        }

        #endregion

        #region 查询

        private void bpsvResultDataGrid_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex < 0) return;
            using (new ControlAnimatorObject(bpsvResultDataGrid))
            {
                var row = bpsvResultDataGrid.Rows[e.RowIndex];
                var bpsvType = row.Tag as BPSVType;
                if (bpsvType == null) return;
                bool useDataContract = SettingManagement.Instance.Setting.DefaultUseDataContract;
                int requestDataMaxExpandDepth = SettingManagement.Instance.Setting.DefaultRequestDataMaxExpandDepth;
                var proxyData = ProxyData.GetProxyData(bpsvType, useDataContract, requestDataMaxExpandDepth);
                if (proxyData == null) return;
                var tabPageName = GetNewTabPageName(bpsvType.DisplayName);
                proxyTabControl.AddProxyTabPage(tabPageName, proxyData);
            }
        }

        /// <summary>
        ///     创建tabPage名称
        /// </summary>
        /// <param name="tabPageName"></param>
        /// <returns></returns>
        private string GetNewTabPageName(string tabPageName)
        {
            var pageNames = new List<string>();
            foreach (TabPage tabPage in proxyTabControl.TabPages)
            {
                if (tabPage.Text.StartsWith(tabPageName))
                    pageNames.Add(tabPage.Text.Trim());
            }

            if (pageNames.Count == 0) return tabPageName;
            var i = 0;
            while (true)
            {
                i++;
                var newPageName = tabPageName + i;
                if (!pageNames.Contains(newPageName)) return newPageName;
            }
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            using (new ControlAnimatorObject(btnQuery))
            {
                btnQuery.Text = string.Format("查 询({0})", 0);
                var queryString = txtBPName.Text;
                if (string.IsNullOrWhiteSpace(queryString)) return;
                bpsvResultDataGrid.Rows.Clear();
                var bpsvTypeList = ProxyTestService.QueryBPSV(queryString);
                if (bpsvTypeList == null || bpsvTypeList.Count == 0) return;
                btnQuery.Text = string.Format("查 询({0})", bpsvTypeList.Count);
                foreach (var bpsvType in bpsvTypeList)
                {
                    var index = bpsvResultDataGrid.Rows.Add();
                    var gridRow = bpsvResultDataGrid.Rows[index];
                    gridRow.Tag = bpsvType;
                    gridRow.Cells["DisplayName"].Value = bpsvType.DisplayName;
                    gridRow.Cells["FullName"].Value = bpsvType.FullName;
                    gridRow.Cells["AssemblyName"].Value = bpsvType.AssemblyName;
                    gridRow.Cells["Kind"].Value = bpsvType.Kind;
                    gridRow.Cells["TransactionType"].Value = bpsvType.TransactionType;
                }
            }
        }

        private void txtBPName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnQuery_Click(sender, e);
            }
        }

        #endregion
    }
}